package com.ruoyi.project.digital.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.rmi.ServerException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class Test {
    public static void main(String[] args) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        try (CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setSSLSocketFactory(getSslConnectionSocketFactory())
                .build()) {
            submit(httpClient, getHttpPost());
        }
    }

    private static void submit(CloseableHttpClient httpClient, HttpPost post) throws IOException {
        Scanner scanner = new Scanner(System.in);
        String question;
        while (true) {
            System.out.print("You: ");
            question = scanner.nextLine();
            System.out.print("AI: ");
            StringEntity stringEntity = new StringEntity(getRequestJson(question), getContentType());
            post.setEntity(stringEntity);  //????????????
            CloseableHttpResponse response;
            response = httpClient.execute(post); //?????????????
            printAnswer(response);
        }
    }


    private static void printAnswer(CloseableHttpResponse response) throws IOException {
        String responseJson = EntityUtils.toString(response.getEntity());
        Answer answer = JSON.parseObject(responseJson, Answer.class);
        System.out.println(answer);
        List<String> answerinfo = new ArrayList<>();
        List<Choices> choices = answer.getChoices();
        for (Choices choice : choices) {
            answerinfo.add(choice.getMessage().get(0).getRole());
            answerinfo.add(choice.getMessage().get(0).getContent());
        }

        System.out.println("role?" + answerinfo.get(0) + "?" + "content" + answerinfo.get(1)); //????
    }


    private static ContentType getContentType() {
        return ContentType.create("text/json", "UTF-8");
    }


    private static String getRequestJson(String question) {
// ??????
        JSONObject messageContent = new JSONObject();
        messageContent.put("role", "user");
        messageContent.put("content", question);

// ??????
        JSONArray messages = new JSONArray();
        messages.add(messageContent);


        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "gpt-3.5-turbo");
        requestBody.put("messages", messages);
        requestBody.put("temperature", 0.7);

        return JSONObject.toJSONString(requestBody, SerializerFeature.WriteMapNullValue);
    }


    private static HttpPost getHttpPost() throws IOException {

        String openAiKey = "sk-VzVZ6IYyAHCG3I734e62CfCb3c154167B39b62316045B771"; //OpenAI??KEY?????????
        int connectTimeout = 600000; //??????
        int connectionRequestTimeout = 600000; //??????
        int socketTimeout = 600000; //socket??????
        HttpPost post = new HttpPost("https://api.opendevelop.tech/v1/chat/completions");
        post.addHeader("Content-Type", "application/json");
        post.addHeader("Authorization", "Bearer " + openAiKey);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectionRequestTimeout)

                .setSocketTimeout(socketTimeout)
                .build();
        post.setConfig(requestConfig);
        return post;
    }


    private static SSLConnectionSocketFactory getSslConnectionSocketFactory() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, s) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        return new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
    }
}
